//
//  NLRefreshView.swift
//  sinaWeibo7110
//
//  Created by 安静清晨 on 2017/1/12.
//  Copyright © 2017年 walk-in-minds. All rights reserved.
//

import UIKit



enum NLstatus{
    
    case Normal
    case Ready
    case Refreshing
    
}


class NLRefreshview: UIControl {
    

//    var daisy : uiactivity
    

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -60, width: ScreenWidth, height: 60))
        
        setupUI()
        backgroundColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
        
        
    }
                            //要先赋个值 flag
    var status : NLstatus = .Normal {
        
        didSet{
            
            switch status {
                
            case .Normal:
//                print("不动")
                self.refreshLbl.text = "可下拉来刷新"
                //箭头变回原样
                UIView.animate(withDuration: 1.2, animations: {
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
                self.daisy.stopAnimating()
                self.arrowIcon.isHidden = false
                
            case .Ready:
                print("准备")
                self.refreshLbl.text = "松手刷新"
                //箭头回转
                UIView.animate(withDuration: 1.2, animations: {
                    self.arrowIcon.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                
                
            case .Refreshing:
                print("刷新了")
                self.refreshLbl.text = "正在刷新"
                self.arrowIcon.isHidden = true
                self.daisy.startAnimating()
                //网络加载新数据. 在tableview那一端接收
                sendActions(for: .valueChanged)
//                设置悬停效果---通过修改tableView的Inset
                UIView.animate(withDuration: 1, animations: {
                    
                    self.mySuperView?.contentInset = UIEdgeInsetsMake(120, 0, 0, 0)
                    
                })
                

            
            
        }
        
        
    }
    
    
    }
    
    
    func backToNormal(){
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute:
            {
                
                self.status = .Normal
                UIView.animate(withDuration: 1, animations: {
                    
                    self.mySuperView?.contentInset = UIEdgeInsetsMake(60, 0, 0, 0)
                    
                })
        })
        
     
    }
    
    
    
    //得到tableview
    override func willMove(toSuperview newSuperview: UIView?) {
        
        super.willMove(toSuperview: newSuperview)
        //判断如果父视图是scrollView.KVO监听contentOffset
        if let superView = newSuperview as? UIScrollView{
            //记录
            self.mySuperView = superView as! UIScrollView
            
            //添加监听
            superView.addObserver(self, forKeyPath: "contentOffset", options:
                [.new], context: nil)
        
            
        }
        
        
        
    }
    

    //接受变化的监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
    
//        
        let offsetY = self.mySuperView?.contentOffset.y ?? 0
//        print(self.mySuperView ?? 66666666666)
        //在拉动
        if self.mySuperView?.isDragging == true {
            
            if offsetY < -124 {
        
                self.status = .Ready
                
            }else{
//
                self.status = .Normal
            }
            
        }else{
            
            //没有拉
            //*************************
            if self.status == .Ready {
                //*********************
                self.status = .Refreshing
            }
        }
        
        
        
        
        
        
        
        
        
    }
    
   
    
    
    
    func setupUI(){
        
        addSubview(refreshLbl)
        addSubview(daisy)
        addSubview(arrowIcon)
        //print(daisy)
        
    
        
        refreshLbl.snp.makeConstraints { (make) in
            
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(20)
        }
        
        daisy.snp.makeConstraints { (make) in
            
            make.centerY.equalTo(refreshLbl)
            make.trailing.equalTo(refreshLbl.snp.leading)
            
        }
        arrowIcon.snp.makeConstraints { (make) in
            
            make.centerY.equalTo(refreshLbl)
            make.trailing.equalTo(refreshLbl.snp.leading)
            
        }
        
    }
    
    
    lazy var refreshLbl : UILabel = {
        
        
        let label = UILabel(title: "下拉刷新", BGImageName: "", size: 14, color: UIColor.darkGray)
        
        return label
        
    }()
    
    lazy var arrowIcon : UIImageView = {
        
        let arrow = UIImageView(image:#imageLiteral(resourceName: "tableview_pull_refresh"))
        return arrow
    }()
    
    lazy var daisy : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    var mySuperView:UIScrollView?
    
    
    
    //移除监听方法
    deinit {
        self.mySuperView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
}


